package com.tensquare.user.controller;

import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.user.annotation.PreAuthorize;
import com.tensquare.user.dto.ReqRole;
import com.tensquare.user.pojo.TbPermission;
import com.tensquare.user.service.PermissionService;
import com.tensquare.user.service.TbRoleService;
import com.tensquare.user.vo.Permission;
import com.tensquare.user.vo.Role;
import com.tensquare.util.DateUtils;
import com.tensquare.util.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "role")
public class RoleController {

    @Autowired
    private TbRoleService roleService;
    @Autowired
    private PermissionService permissionService;

    @RequestMapping(value = "/find/{id}", method = RequestMethod.GET)
    public Result findOne(@PathVariable(value = "id") Integer id) {
        Role role = roleService.findOne(id);
        return new Result(true, "查询成功", StatusCode.OK, role);
    }

    /**
     * 添加角色
     *
     * @param reqRole 角色信息
     */
    @PreAuthorize(hasPermission = "role:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addRole(@RequestBody ReqRole reqRole) {
        roleService.addRole(reqRole);
        return new Result(true, "添加成功", StatusCode.OK);
    }

    /**
     * 删除角色
     *
     * @param map ids：角色Id合集
     * @return
     */
    @PreAuthorize(hasPermission = "role:del")
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delRole(@RequestBody Map<String, ArrayList<Integer>> map) {
        ArrayList<Integer> ids = map.get("ids");
        if (null == ids || ids.size() == 0) {
            return new Result(false, "id不能为空", StatusCode.PARAMS_IN_ERROR);
        }
        roleService.delRole(ids);
        return new Result(true, "删除成功", StatusCode.OK);
    }

    /**
     * 分页查询角色信息
     */
    @PreAuthorize(hasPermission = "role:list")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result findByPage(@RequestBody Map<String, Object> map) {
        String createDate = (String) map.get("createDate");
        Date beginCreateDate = null;
        Date endCreateDate = null;
        if (!StringHelper.isEmpty(createDate)) {
            String[] createDates = createDate.split("~");
            beginCreateDate = DateUtils.parse(DateUtils.FormatType.type1, createDates[0]);
            endCreateDate = DateUtils.parse(DateUtils.FormatType.type1, createDates[1]);
        }
        Integer offset = (Integer) map.get("offset");
        Integer limit = (Integer) map.get("limit");
        String roleName = (String) map.get("roleName");
        String roleCode = (String) map.get("roleCode");
        String roleStatus = (String) map.get("roleStatus");
        return new Result(true, "查询成功", StatusCode.OK, roleService.findByPage(offset, limit, roleName, roleCode, roleStatus, beginCreateDate, endCreateDate));
    }

    /**
     * 修改角色添加权限
     * @param map
     * @return
     */
    @PreAuthorize(hasPermission = "role:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(@RequestBody Map<String, Object> map) {
        Integer roleId = (Integer) map.get("roleId");
        ArrayList<Integer> permissionIds = (ArrayList<Integer>) map.get("permissionIds");
        Map<String,Object> columns = (Map<String, Object>) map.get("columns");
        if (null == roleId) {
            return new Result(false, "角色Id不能为空", StatusCode.PARAMS_IN_ERROR);
        }
        roleService.updateRole(roleId,permissionIds,columns);
        return new Result(true, "修改成功", StatusCode.OK);
    }

    /**
     * 修改角色状态
     *
     * @param map disable:状态0：启用，1停用 ,roleId:角色Id
     */
    @PreAuthorize(hasPermission = "role:update")
    @RequestMapping(value = "/changeDisable", method = RequestMethod.POST)
    public Result changeDisable(@RequestBody Map<String, Object> map) {
        String disable = (String) map.get("disable");
        Integer roleId = (Integer) map.get("roleId");
        roleService.changeDisable(disable, roleId);
        return new Result(true, "修改成功", StatusCode.OK);
    }

    /**
     * 添加用户的权限
     *
     * @param map userId:用户Id，roleIds角色的Id合集
     */
    @PreAuthorize(hasPermission = "role:addUser")
    @RequestMapping(value = "/update/userRole", method = RequestMethod.POST)
    public Result updateRoleToUser(@RequestBody Map<String, Object> map) {
        String userId = (String) map.get("userId");
        ArrayList<Integer> roleIds = (ArrayList<Integer>) map.get("roleIds");
        if (userId == null || userId.equals("")) {
            return new Result(false, "用户Id不能为空", StatusCode.PARAMS_IN_ERROR);
        }
        if (null == roleIds || roleIds.size() == 0) {
            return new Result(false, "角色Id不能为空", StatusCode.PARAMS_IN_ERROR);
        }
        roleService.updateRoleToUser(roleIds, userId);
        return new Result(true, "修改成功", StatusCode.OK);
    }

    /**
     * 分页获取拥有该角色的用户
     */
    @PreAuthorize(hasPermission = "role:findUser")
    @RequestMapping(value = "/find/user", method = RequestMethod.POST)
    public Result getUserByRole(@RequestBody Map<String, Object> map) {
        Integer roleId = (Integer) map.get("roleId");
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");
        String nickname = (String) map.get("nickname");
        String mobile = (String) map.get("mobile");
        if (roleId == null || roleId <= 0) {
            return new Result(false, "角色Id异常", StatusCode.PARAMS_IN_ERROR);
        }
        return new Result(true, "查询成功", StatusCode.OK, roleService.findUserByRole(roleId, pageNum, pageSize, nickname, mobile));
    }

    /**
     * 删除该用户的角色
     *
     * @param map roleId 角色id，userIds用户Id的集合
     */
    @PreAuthorize(hasPermission = "role:cancelAuth")
    @RequestMapping(value = "/cancelAuth", method = RequestMethod.POST)
    public Result cancelRoleAuth(@RequestBody Map<String, Object> map) {
        Integer roleId = (Integer) map.get("roleId");
        ArrayList<String> userIds = (ArrayList<String>) map.get("userIds");
        if (roleId == null || roleId <= 0) {
            return new Result(false, "角色Id异常", StatusCode.PARAMS_IN_ERROR);
        }
        if (userIds == null || userIds.size() <= 0) {
            return new Result(false, "用户Id异常", StatusCode.PARAMS_IN_ERROR);
        }
        roleService.delUserRoleByUserIds(roleId, userIds);
        return new Result(true, "删除成功", StatusCode.OK);
    }

    /**
     * 分页获取不拥有该权限的用户
     */
    @PreAuthorize(hasPermission = "role:findUser")
    @RequestMapping(value = "/find/notUser", method = RequestMethod.POST)
    public Result getUserNotInRole(@RequestBody Map<String, Object> map) {
        String nickName = (String) map.get("nickname");
        String mobile = (String) map.get("mobile");
        Integer roleId = (Integer) map.get("roleId");
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");
        if (roleId == null || roleId <= 0) {
            return new Result(false, "角色Id异常", StatusCode.PARAMS_IN_ERROR);
        }
        return new Result(true, "查询成功", StatusCode.OK, roleService.findUserNotInRole(roleId, pageNum, pageSize, nickName, mobile));
    }

    @PreAuthorize(hasPermission = "role:addUser")
    @RequestMapping(value = "/add/user", method = RequestMethod.POST)
    public Result addRoleToUsers(@RequestBody Map<String, Object> map) {
        ArrayList<String> userIds = (ArrayList<String>) map.get("userIds");
        Integer roleId = (Integer) map.get("roleId");
        if (roleId == null || roleId <= 0) {
            return new Result(false, "角色Id异常", StatusCode.PARAMS_IN_ERROR);
        }
        if (userIds == null || userIds.size() == 0) {
            return new Result(false, "用户Id不能为空", StatusCode.PARAMS_IN_ERROR);
        }
        roleService.addRoleToUser(roleId, userIds);
        return new Result(true, "添加成功", StatusCode.OK);
    }
}
